package com.itheima.web;


import com.itheima.utils.OSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class UploadController {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/upload")
    public String upload(@RequestParam("myFile")MultipartFile multipartFile) throws IOException {
        String objectName = OSSUtils.upload(multipartFile.getInputStream(),UUID.randomUUID().toString()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")));
        redisTemplate.opsForSet().add("file:templateRubbish",objectName);
        redisTemplate.opsForValue().set("file:"+objectName,1,30, TimeUnit.SECONDS);
        return objectName;
    }


    @RequestMapping ("/download")
    public void download(HttpServletResponse response) throws IOException {
        ServletOutputStream out = response.getOutputStream();
        System.out.println("1111111111");
        FileInputStream input = new FileInputStream("C:\\Users\\Sun\\Desktop\\sun.xlsx");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            baos.write(buffer, 0, n);
        }

        byte[] xlsBytes = baos.toByteArray();
        out.write( xlsBytes);
        out.close();
    }


}
